const request = require("request");
const vscode = require("vscode");

function login(username, password) {
    // execution
    var my_jar = request.jar();
    my_jar.setCookie('https://zjuam.zju.edu.cn', username + password);
    var url = 'https://zjuam.zju.edu.cn/cas/login?service=https%3A%2F%2Fhealthreport.zju.edu.cn%2Fa_zju%2Fapi%2Fsso%2Findex%3Fredirect%3Dhttps%253A%252F%252Fhealthreport.zju.edu.cn%252Fncov%252Fwap%252Fdefault%252Findex';
    var options = {
        'method': 'GET',
        'url': url,
        'jar': my_jar
    };
    return new Promise((resolve) => {
        // resolve 是登录成功后的函数
        request(options, function (error, response) {
            if (error) throw new Error(error);
            // console.log(response.body);
            let body = response.body;
            // var cookie_string = j.getCookieString(url); // "key1=value1; key2=value2; ..."
            // var cookies = j.getCookies(url);
            // console.log(cookies);
            let reg = /name="execution" value="(.*?)"/;
            var execution = body.match(reg)[1];
            
            // password
            var options = {
                'method': 'GET',
                'url': 'https://zjuam.zju.edu.cn/cas/v2/getPubKey',
                'jar': my_jar
            };
            request(options, function (error, response) {
                if (error) throw new Error(error);
                // console.log(response.body);
                var res = JSON.parse(response.body);
                let M_str = res['modulus'];
                var e_str = res['exponent'];
                function Str2BytesInt(str) {
                    let buf = '0x';
                    for (let i in str) {
                        let code = str.charCodeAt(i);
                        buf += code.toString(16);
                    }
                    return BigInt(buf);
                };
                var password_int = Str2BytesInt(password)
                var e_int = parseInt(e_str, 16);
                var M_int = BigInt('0x' + M_str);
                function my_pow(a, b, c) {
                    var ans = BigInt(1);
                    while (b > 0) {
                        if (b & 1) {
                            ans = ans * a % c;
                        }
                        a = a * a % c;
                        b = Math.floor(b / 2);
                    }
                    return ans;
                }
                var result_int = my_pow(password_int, e_int, M_int);
                var encrypt_password = result_int.toString(16);
                while (encrypt_password.length < 128) {
                    encrypt_password += "0";
                }
                console.log('加密的密码', encrypt_password);
                let form_data = {
                    'username': username,
                    'password': encrypt_password,
                    'execution': execution,
                    '_eventId': 'submit'
                };
                var headers = {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'
                };
                request(options={
                    'url': url,
                    'headers': headers,
                    'method': 'POST',
                    'form': form_data,
                    'jar': my_jar
                }, function (error, response) {
                    if (response.body.search('统一身份认证') == -1) {
                        console.log('登陆成功');
                        
                    } else {
                        // vscode.window.showErrorMessage("登陆失败，请检查用户名和密码")
                        console.log("登陆失败")
                    }
                    request(options={
                        'url': 'https://healthreport.zju.edu.cn/ncov/wap/default/index',
                        'method': 'GET',
                        'headers': headers,
                        'jar': my_jar,
                    }, function(error, response) {
                        if (response.body.search('日常健康报备') != -1) {
                            // progress.report({ increment: 30, message: "登录成功，正在填报" });
                            vscode.window.showInformationMessage("登陆成功，正在填报");
                            resolve({
                                response: response,
                                jar: my_jar,
                                headers: headers});
                        } else {
                            vscode.window.showErrorMessage("登陆失败，请检查用户名和密码")
                        }
                    });
                })
            });
        });
    })
}

exports.login = login;